<?php
/**
 * Created by PhpStorm.
 * User: lengbin
 * Date: 2018/6/21
 * Time: 下午5:00
 */

namespace common\core\actions;

use common\core\base\Action;
use common\helpers\Html;

/**
 * change
 *
 * Class ChangeAction
 * @package common\core\actions
 */
class ChangeAction extends Action
{
    /**
     * request param
     *
     * @var string
     */
    public $modelByParam = 'id';

    /**
     *  call_user_func
     * @var string
     */
    public $change;
    /**
     * message
     * @var string
     */
    public $message;

    /**
     *  validate filed
     *
     * @var array
     */
    public $validateFiled;

    public function init()
    {
        parent::init();

        if ($this->message === null) {
            $this->message = '修改';
        }
    }

    public function run()
    {
        if (\Yii::$app->request->isPost) {
            $id = \Yii::$app->request->post($this->modelByParam);
        } else {
            $id = \Yii::$app->request->get($this->modelByParam);
        }

        try {
            $model = call_user_func($this->change, $id);
            // if return model
            if (is_object($model)) {
                if ($model->validate($this->validateFiled)) {
                    $this->successAlert($this->message . '成功');
                } else {
                    $this->errorAlert($this->getError($model));
                }
            } else {
                if ($model) {
                    $this->successAlert($this->message . '成功');
                } else {
                    $this->errorAlert($this->message . '失败');
                }
            }
        } catch (\Exception $exception) {
            $str = str_replace(PHP_EOL, '', Html::encode($exception->getMessage()));
            $this->errorAlert($str);
        }

        return $this->redirect();
    }
}